#ifndef UTIL_H
#define UTIL_H

#include <string>
#include <fstream>
#include <vector>
#include <map>

#ifndef SAFE_DELETE
#define SAFE_DELETE(p)       { if (p) { delete (p);     (p)=NULL; } }
#endif    
#ifndef SAFE_DELETE_ARRAY
#define SAFE_DELETE_ARRAY(p) { if (p) { delete[] (p);   (p)=NULL; } }
#endif    
#ifndef SAFE_RELEASE
#define SAFE_RELEASE(p)      { if (p) { (p)->Release(); (p)=NULL; } }
#endif

enum EDirection
{
	Direction_UP = 0,
	Direction_DOWN,
	Direction_LEFT,
	Direction_RIGHT,
};

void WriteString( std::ofstream &f, std::string &s );
void ReadString( std::ifstream &f, std::string &s );
wchar_t * MBToWChar( const char *str );
char * WCharToMB( const wchar_t *str );

class TiXmlElement;

int atoi_s( const char* str , int defaultv = 0);
const char *easyitoa( int i );
__int64 atoi64_s( const char* str, int defaultv = 0 );

float atof_s( const char* str, float defaultv = 0.0f );

float GetXmlFloat( TiXmlElement *pElement, const char *nodeName, float defaultv = 0.0f );

int GetXmlInteger( TiXmlElement *pElement, const char *nodeName, int defaultv = 0 );

__int64 GetXmlInt64( TiXmlElement *pElement, const char *nodeName, int defaultv = 0 );

const char* GetXmlString( TiXmlElement *pElement, const char *nodeName, const char* defaultv = "" );
void renderRectangle(float x1, float y1, float x2, float y2, int color = 0xff000000, bool solid = false, float z=0.5f);
void renderTriangle(float x1, float y1, float x2, float y2, float x3, float y3, int color = 0xff000000, bool solid = false, float z=0.5f);
void renderCursor();

int loadTexture( std::string filename );
const char *GeneratePath( const char *pathtype, const char *filename );
void showDialog( const char *content );
void splitToVector( const char *str, std::vector<int>& vec );
void splitToMap( const char *str, std::map<int,int>& m );

template <typename T>
void Truncate( T &value, T minvalue, T maxvalue )
{
	if( value > maxvalue )
		value = maxvalue;
	if( value < minvalue )
		value = minvalue;
}

typedef bool ( *renderfunc )(void);
typedef bool ( *framefunc )(void);
typedef std::vector<renderfunc> RenderStack;
typedef std::vector<framefunc> FrameStack;
void PushGameStack( renderfunc render, framefunc frame );
void PopGameStack( );
extern RenderStack renders;
extern FrameStack frames;
#endif